package com.truyentranh.modules.truyentranh;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.truyentranh.R;
import com.truyentranh.controls.DataCachedControl;
import com.truyentranh.controls.IOnComicChanged;
import com.truyentranh.controls.IOnFinalPage;
import com.truyentranh.controls.ImagePagerAdapter;
import com.truyentranh.controls.OnSaveComic;
import com.truyentranh.controls.onSocialAction;
import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.main.ComicBussiness;
import com.truyentranh.main.DisplayUtils;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.TruyenTranhRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.FaceBookUtils;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.StringUtils;
import com.truyentranh.utils.Utils;
import com.truyentranh.utils.sqllite.datasource.TopicHaiBlData;
import com.truyentranh.utils.sqllite.datasource.TruyenTranhBookmark;

public class TruyenTranhViewActivity extends Activity implements RequestListener, IOnFinalPage, onSocialAction, IOnComicChanged {

	private ImagePagerAdapter imageComicAdapter;
	String idModules = "";
	String nameTitle = "";
	int index = 0;
	private ArrayList<TruyenTranhBookmark> bookmarks;
	boolean foundInDatabase = false;
	@Override
	protected void onDestroy() {
		if(imageComicAdapter != null){
			imageComicAdapter.clearListener();
		}
		super.onDestroy();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.truyentranh_activity_layout);
		init();

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			idModules = extras.getString("href");
			nameTitle = extras.getString("NAME");
			index = extras.getInt("index");

			Logger.logMe("id = " + idModules);
		}
		
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					doBack();
				}
			});
		}
		
		bookmarks = TruyenTranhSession.getBookmark(this);
	}
	
	void doBack() {
		if (imageComicAdapter != null && imageComicAdapter.isFinalItem()) {
			if(foundInDatabase && imageComicAdapter.isFinalItem()){
				TruyenTranhSession.deleteBookmark(this, idModules);
				Log.i("TruyenTranhViewAct", "deleteBookmarkdeleteBookmarkdeleteBookmark");
			}
			finish();
			return;
		}

		//auto bookmark
		if(imageComicAdapter.getCurrentViewIndex() > 1){
			TruyenTranhSession.setCurrentPage(imageComicAdapter.getCurrentViewIndex());
			TruyenTranhSession.doSaveCurrentSession(TruyenTranhViewActivity.this);
		}		
		finish();
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int itemId = item != null ? item.getItemId() : -1;
		switch (itemId) {
		case 1:
			Logger.logMe("Save default");
			ComicBussiness.getInstance(TruyenTranhViewActivity.this).doSaveCommicToDefault(TruyenTranhViewActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {

				@Override
				public void onError(int errorCode) {
					processError(errorCode);
				}

				@Override
				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					// TODO Auto-generated
					// method stub

				}

				@Override
				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
				}
			});
			break;
		case 2:
			Utils.downloadPhoto(this, 0, this, imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		case 3:
			Logger.logMe("facebook");
			FaceBookUtils.doShareFaceBookComic(imageComicAdapter.getCurrentData(), TruyenTranhViewActivity.this);
			break;
		case 4:
			doRefreshPage();
			Logger.logMe("refresh");
			break;
		case 5 :
			FaceBookUtils.doShareApplication(this);
			break;
		case 6 :
			doComment(imageComicAdapter.getCurrentData());
			break;
		case 7 :
			Utils.setWallpaper(this, 0, this,  imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		}
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (ComicBussiness.getInstance(this).getDefaultComicTopic() != null && ComicBussiness.getInstance(this).getDefaultComicTopic().getId() != -1) {
			menu.add(1, 1, 1, "Lưu " + ComicBussiness.getInstance(this).getDefaultComicTopic().getName()).setIcon(R.drawable.ic_save_default);
		}
		menu.add(1, 2, 2, "Lưu").setIcon(R.drawable.ic_saved);
		menu.add(3, 3, 3, "Facebook").setIcon(R.drawable.ic_facebook);
		menu.add(4, 4, 4, "Tải lại").setIcon(R.drawable.ic_refresh);
		menu.add(5, 5, 5, "Chia sẻ App").setIcon(R.drawable.ic_share);
		menu.add(5, 6, 6, "Bình luận").setIcon(R.drawable.ic_comment);
		menu.add(6, 7, 5, "Đặt hình nền").setIcon(R.drawable.ic_wall);
		return super.onCreateOptionsMenu(menu);
	}

	void doAdsByServer() {
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			doBack();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void processError(int errorCode) {
		String error = "";
		switch (errorCode) {

		case OnSaveComic.CREATE_TOPIC_ERROR:
			error = "Không thể tạo được chủ đ�?.";
			break;
		case OnSaveComic.DB_NOT_FOUND:
			error = "Không tìm thấy tập tin dữ liệu.";
			break;
		case OnSaveComic.DEFAULT_TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�? mặc định.";
			break;
		case OnSaveComic.IMAGE_NOT_FOUND:
			error = "Không có truyện hiển thị.";
			break;
		case OnSaveComic.INSERT_COMIC_ERROR:
			error = "Không thể thêm truyện vào máy.";
			break;
		case OnSaveComic.TOPIC_NAME_INVAILD:
			error = "Tên chủ đ�? không đúng.";
			break;
		case OnSaveComic.TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�?.";
			break;
		}
		if(!error.equals("")){
			Toast.makeText(TruyenTranhViewActivity.this, error, 1000).show();
		}
	}

	void showNotice(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("�?óng", null);

		AlertDialog notice = builder.create();
		notice.show();
	}

	void doRefreshPage() {
		onStartUp();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	private int lastId = -1;
	long currentRequestId = -1;

	void init() {
	}

	void getComicFromServer(RequestListener listener) {
		TruyenTranhRequester requester = TruyenTranhRequester.getComicImage(idModules, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		requester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(requester);
	}

	private void doComment(final HaiBLMetalData blMetalData) {
		Intent intent = new Intent(getApplication(), TruyenTranhCommentActivity.class);
		intent.putExtra("href", "http://haibl.net/public/truyentranh?comment="+StringUtils.MD5(imageComicAdapter.getCurrentData().getImageUrl()));
		startActivity(intent);
	}

	@Override
	public void commicChanged(HaiBLMetalData blMetalData) {
		if(blMetalData != null){
			if(imageComicAdapter != null && imageComicAdapter.isFinalItem()){
				ArrayList<TruyenTranhChapterData> cachedList = (ArrayList<TruyenTranhChapterData>) DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
				if (cachedList != null && !cachedList.isEmpty()) {
					if(index + 1 < cachedList.size()){
						btnNextChapter.setVisibility(View.VISIBLE);
					}
				}
			} else {
				btnNextChapter.setVisibility(View.GONE);
			}

			if(pageStatus != null){
				int currentIndex = imageComicAdapter.getCurrentViewIndex() + 1;
				int size = imageComicAdapter.getCount();
				String text = currentIndex + "/" + size;
				pageStatus.setText(text);
			}


//			if(imageDescription != null){
//				imageDescription.setText(blMetalData.getTitleDescription());
//			}
//			if (commentView != null) {
//				String comment = getResources().getString(R.string.comment_string);
//				if(!blMetalData.getCommentCount().equals(""))
//					comment = blMetalData.getCommentCount() + " " + comment;
//				commentView.setText(comment);
//			}
		}
	}

	OnClickListener nextChapterClick = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			ArrayList<TruyenTranhChapterData> cachedList = (ArrayList<TruyenTranhChapterData>) DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
			if (cachedList != null && !cachedList.isEmpty()) {
				index += 1;
				if(index < cachedList.size()){
					TruyenTranhChapterData diemMetalData = cachedList.get(index);

					final String href = diemMetalData.getUrl();
					if (href != null && !"".equals(href)) {
						
						if(foundInDatabase){
							TruyenTranhSession.deleteBookmark(TruyenTranhViewActivity.this, idModules);
							Log.i("TruyenTranhViewAct", "deleteBookmarkdeleteBookmarkdeleteBookmark");
						}						
						finish();

						Intent intent = new Intent(getApplication(), TruyenTranhViewActivity.class);
						intent.putExtra("href", href);
						intent.putExtra("NAME", diemMetalData.getName());
						intent.putExtra("index", index);

						startActivity(intent);
					}
				}
			}
		}
	};


	OnClickListener doShareFB = new OnClickListener() {

		@Override
		public void onClick(View v) {			
//				Intent intent = new Intent(getApplication(), TruyenTranhCommentActivity.class);
//				intent.putExtra("href", "http://haibl.net/public/truyentranh?comment="+StringUtils.MD5(imageComicAdapter.getCurrentData().getImageUrl()));
//				startActivity(intent);
				openOptionsMenu();
			}
	};

	Button btnNextChapter = null;
	ViewPager viewPager = null;
	LinearLayout loading = null;
	LinearLayout loadingError = null;
	ImageButton menuButton;
	TextView pageStatus = null;
	public void onStartUp() {
		pageStatus = (TextView)findViewById(R.id.pageStatus);
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		btnNextChapter = (Button) findViewById(R.id.btnNextChapter);
		viewPager = (ViewPager) findViewById(R.id.view_pager);
		loading = (LinearLayout) findViewById(R.id.loadingpage);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);

		menuButton.setOnClickListener(doShareFB);
		btnNextChapter.setOnClickListener(nextChapterClick);

		loadingError.setVisibility(View.INVISIBLE);
		viewPager.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);
		btnNextChapter.setVisibility(View.GONE);

		if(imageComicAdapter == null){
			imageComicAdapter = new ImagePagerAdapter(this);
			imageComicAdapter.noFit = true;
			imageComicAdapter.setOnFinalPage(this);
			imageComicAdapter.setComicChanged(this);
		}
		viewPager.setOnPageChangeListener(imageComicAdapter);
		imageComicAdapter.clearData();
		RequestListener listener =  new RequestListener() {

			@Override
			public void onRequestFailed(String errorMsg, Request request) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						imageComicAdapter.clearData();
						loading.setVisibility(View.GONE);
						loadingError.setVisibility(View.VISIBLE);
						doAdsByServer();
					}
				});
			}

			@Override
			public void onRequestComplete(Request request) {
				// TODO Auto-generated method stub
				if(request instanceof TruyenTranhRequester && currentRequestId == request.getRequestId()){
					ArrayList<HaiBLMetalData> datas = new ArrayList<HaiBLMetalData>();
					TruyenTranhRequester r = (TruyenTranhRequester)request;
					JSONObject jsonObject = r.getData();
					try{
						if(jsonObject != null){
							String imageUrl = jsonObject.has("imageUrl") ? jsonObject.getString("imageUrl") : "";

							JSONArray array = jsonObject.has("imageList") ? jsonObject.getJSONArray("imageList") : null;
							if(array != null){
								for(int i = 0 , n = array.length() ; i < n ; i++){
									JSONObject child = array.getJSONObject(i);
									String img = child.has("image") ? child.getString("image") : "";
									img = imageUrl + "/" + img;
									HaiBLMetalData blMetalData = new HaiBLMetalData();
									blMetalData.setBigImageUrl(img);
									blMetalData.setImageUrl(img);

									datas.add(blMetalData);
								}
							}
						}
					}catch(Exception e){

					}

					imageComicAdapter.setMetalData(datas);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							loading.setVisibility(View.GONE);
							viewPager.setVisibility(View.VISIBLE);
							viewPager.setAdapter(imageComicAdapter);
							
							String id = StringUtils.MD5(idModules).trim();
							int page = 0;
							if(bookmarks != null){
								Log.i("TruyenTranhViewAct", "bookmarks read");
								int n = bookmarks.size();
								for(int i = 0 ; i < n ; i++){
									TruyenTranhBookmark bookmark = bookmarks.get(i);
									Log.i("TruyenTranhViewAct", ">>>"+bookmark.getCurrentChapter().id);
									Log.i("TruyenTranhViewAct", ">>>id = "+id);
									if(bookmark.getCurrentChapter().id.equals(id)){
										foundInDatabase = true;
										page = bookmark.getCurrentPage();
										break;
									}
								}
							}
							Log.i("TruyenTranhViewAct", ">>>page = "+page);
							imageComicAdapter.onPageSelected(page);
							viewPager.setCurrentItem(page);
							
							viewPager.invalidate();
							doAdsByServer();
						}
					});
				}
			}
		};
		//khi doi tab can reset lai so page
		//cached lai nhu the nao
		getComicFromServer(listener);
	}

	@Override
	public void onRequestComplete(Request request) {

	}

	@Override
	public void onRequestFailed(String errorMsg, Request request) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFinalPage() {

	}

	@Override
	public void onComment(HaiBLMetalData data) {
		doComment(data);
	}

	@Override
	public void onLike(HaiBLMetalData data) {
		// TODO Auto-generated method stub

	}

	int countAds = 0;
	@Override
	public void onFinalItem(HaiBLMetalData data) {

	}
}
